function _ajax(options){

    return new Promise((resolve,reject) =>{
        let data  = options.data == " " ?  null : options.data;

        
        let method = options.method == "post" ? "post" : "get";
        
        let keyname  = Object.keys(data);
        let a = "";
        keyname.forEach(ele => {
            a += `${ele}=${data[ele]}&`
            return a;
        }) 
        //如果为get就拼接在url，不然就拼接在data
        let params = null;
        if(method == "get"){
            params = options.url +"?"+ a;
            params = params.substring(0,params.length-1);
        }else{
            params = options.url;   
            data = a.substring(0,a.length-1);
            
        }   
    
        // alert(data)
    
        let xhr = new XMLHttpRequest();
        xhr.open(method,params);
        console.log(data);
    
        //是post请求就加请求头
        if(method == "post"){
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send(data);
        }else{
           xhr.send() 
        }
    
        xhr.addEventListener('readystatechange',() => {
    
            if(xhr.readyState == 4){
                if(xhr.status == 200)resolve(JSON.parse(xhr.responseText))
                else reject('请求失败')
            }
            
        })
    })

}


async function getData(url,data1,method){
    let res = await _ajax({
        url : url,
        data : data1,
        method:method
    })
    // console.log(url,data1,method);
    return res
}

export {getData,_ajax}